#include <QtGui>
#include "twitlist.h"

TwitList::TwitList(QWidget *parent):
        QWidget(parent)
{
    locale = new QLocale(QLocale::English);

    getImage = new GetImage(this);

    mainLayout = new QVBoxLayout();
    mainLayout->setMargin(0);
    mainLayout->setSpacing(0);
    mainLayout->insertStretch(201,1);

    setLayout(mainLayout);

    connect(getImage, SIGNAL(imageReady(QString,QPixmap)), this, SLOT(setImage(QString,QPixmap)));
}

void TwitList::createList(QLinkedList<Returnables::StatusElement*> list)
{
    deleteList();

    Returnables::StatusElement *statusElement = NULL;
    TwitListItem *item = NULL;
    IDS *ids = NULL;
    int pos = 0;

    while (!list.isEmpty())
    {
        statusElement = list.takeFirst();
        item = new TwitListItem(this);

            item->SetIndPosition(pos);

            item->changeCreatedAt("<a href=\"http://twitter.com/"+statusElement->user.screenName + \
                                  "/status/" + QString::number(statusElement->status.id) + \
                                  "\" style=\"color:#999999; text-decoration: none;\">" + \
                                  formatTime(statusElement->status.createdAt)+"</a>");

            item->changeSource(formatSource(statusElement->status.source));
            item->changeStatus(formatStatus(statusElement->status.text, statusElement->user.screenName));

            item->enableFavorit(statusElement->status.favorited);
            connect(item, SIGNAL(favoritClicked(int,bool)), this, SLOT(emitFavorit(int,bool)));

            if(statusElement->user.id != profile.user.id)
            {
                item->enableReply();
                connect(item, SIGNAL(replyClicked(int)), this, SLOT(emitReply(int)));
            } else {
                item->enableTrash();
                connect(item, SIGNAL(trashClicked(int)), this, SLOT(emitTrash(int)));
            }

        ids = new IDS();
        ids->statusId = statusElement->status.id;
        ids->screenName = statusElement->user.screenName;
        idsList.append(ids);

        mainLayout->insertWidget(pos++, item);
        items.append(item);

        getImage->AddImageData(statusElement->user.screenName, statusElement->user.profileImageUrl);

        item = NULL;
        ids = NULL;
    }
}

void TwitList::emitFavorit(int pos, bool favorited)
{
    emit favoritClicked(idsList.at(pos)->statusId, favorited);
}

void TwitList::emitReply(int pos)
{
    emit replyClicked(idsList.at(pos)->screenName);
}

void TwitList::emitTrash(int pos)
{
    qDebug() << "TwitList::emitTrash(): pos id is " << pos;
    emit TrashClicked(idsList.at(pos)->statusId);
}

void TwitList::updateFavoritedStatus(uint statusId, bool favorited)
{
    for(int i = 0; i < idsList.size(); ++i)
    {
        if(statusId == idsList.at(i)->statusId)
        {
            items.at(i)->enableFavorit(favorited);
            return;
        }
    }
}

void TwitList::removeTrashedStatus(uint statusId)
{
    for(int i = 0; i < idsList.size(); ++i)
    {
        if(statusId == idsList.at(i)->statusId)
        {
            delete items.takeAt(i);
            return;
        }
    }
}

void TwitList::deleteList()
{
    while(!items.isEmpty())
    {
        delete items.takeFirst();
    }
    while(!idsList.isEmpty())
    {
        delete idsList.takeFirst();
    }
}

QString TwitList::formatTime(QString createdAt)
{
    createdAt = createdAt.remove(QRegExp("\\+\\d{4}\\s"));
    QDateTime dateTime = locale->toDateTime(createdAt, "ddd MMM dd HH:mm:ss yyyy");
    dateTime.setTimeSpec(Qt::UTC);
    dateTime.toLocalTime();
    int seconds = dateTime.secsTo(QDateTime::currentDateTime());
    // :-))
    if(seconds < 0) return tr("Just now");
    if( seconds < 60 ) return tr("%n second(s) ago", "", seconds);
    if( seconds < 3600 )
    {
        int minutes = seconds / 60;
        return tr("%n minute(s) ago", "", minutes);
    }
    if ( seconds < 86400 )
    {
        int hours = seconds / 3600;
        return tr("about %n hour(s) ago", "", hours);
    }
    return locale->toString(dateTime, "HH:mm MMM dd");
}

QString TwitList::formatStatus(QString status, QString screenName)
{
    screenName = "<a href=\"http://twitter.com/"+screenName+"\" style=\"color:" + statusOwnerColor + \
                 "; text-decoration: none; font-weight:" + statusOwnerBold + ";\">"+screenName+"</a>";

    QRegExp rxScreenName("(?:@)([\\w\\d\\-]*)");
    QRegExp rxLink("\\b(ftp[\\w\\d\\-/\\.:#]*|https?[\\w\\d\\-/\\.:#]*)\\b");
    QStringList listScreenName;
    QStringList listLink;
    int posScreenName = 0;
    int posLink = 0;
    while((posLink = rxLink.indexIn(status, posLink)) != -1)
    {
        listLink.append(rxLink.cap(1));
        posLink += rxLink.matchedLength();
    }
    while(!listLink.isEmpty())
    {
        QString link = listLink.takeFirst();
        status.replace(link, "<a href=\""+link+"\" style=\"color:" + linksColor + \
                       "; text-decoration: none; font-weight:" + linksBold + ";\">"+link+"</a>");
    }
    while((posScreenName = rxScreenName.indexIn(status, posScreenName)) != -1)
    {
        listScreenName.append(rxScreenName.cap(1));
        posScreenName += rxScreenName.matchedLength();
    }
    while(!listScreenName.isEmpty())
    {
        QString name = listScreenName.takeFirst();
        status.replace("@"+name, "@<a href=\"http://twitter.com/"+name+"\" style=\"color:" + usersColor + \
                       "; text-decoration: none; font-weight:" + usersBold + ";\">"+name+"</a>");
    }

    return screenName+" "+status;
}

QString TwitList::formatSource(QString source)
{
    if(source != "web")
    {
        int indPos = source.indexOf(">");
        return source.insert(indPos, "style=\"color: #999999; text-decoration: none;\"");
    } else {
        return "<a href=\"http://twitter.com/\" style=\"color: #999999; text-decoration: none;\">web</a>";
    }
}

void TwitList::setStatusOwnerColor(const QString &color)
{
    statusOwnerColor = color;
}

void TwitList::setStatusOwnerBold(bool isBold)
{
    isBold ? statusOwnerBold = "bold" : statusOwnerBold = "normal";
}

void TwitList::setUsersColor(const QString &color)
{
    usersColor = color;
}

void TwitList::setUsersBold(bool isBold)
{
    isBold ? usersBold = "bold" : usersBold = "normal";
}

void TwitList::setLinksColor(const QString &color)
{
    linksColor = color;
}

void TwitList::setLinksBold(bool isBold)
{
    isBold ? linksBold = "bold" : linksBold = "normal";
}

void TwitList::setProfile(Returnables::ExtUserInfoElement extProfile)
{
    profile = extProfile;
}

void TwitList::setCacheDir(QString cachedir)
{
    getImage->SetCacheDir(cachedir);
}

void TwitList::setImage(QString screen_name, QPixmap image)
{
    for(int i = 0; i < idsList.size(); ++i)
    {
        if(screen_name == idsList.at(i)->screenName)
        {
            items.at(i)->changeProfileImage(image);
        }
    }
}

TwitList::~TwitList()
{

}
